package com.gale.park.modules.pms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gale.park.common.service.RedisService;
import com.gale.park.modules.pms.dto.TempDTO;
import com.gale.park.modules.pms.mapper.PmsTempMapper;
import com.gale.park.modules.pms.model.PmsTemp;
import com.gale.park.modules.pms.service.PmsTempService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Gale
 * @since 2022-02-16
 */
@Service
public class PmsTempServiceImpl extends ServiceImpl<PmsTempMapper, PmsTemp> implements PmsTempService {
    @Value("${redis.key.prefix.card}")
    private static String REDIS_KEY_PREFIX_CARD_ID;

    @Value("${redis.key.prefix.temp}")
    private static String REDIS_KEY_PREFIX_TEMP_ID;

    @Autowired
    private RedisService redisService;

    @Override
    public Page<PmsTemp> list(TempDTO temp) {
        Page<PmsTemp> page = new Page<>(temp.getPageNum(), temp.getPageSize());

        LambdaQueryWrapper<PmsTemp> queryWrapper = new LambdaQueryWrapper<>();

        return this.page(page, queryWrapper);
    }

    @Override
    public boolean entryParking(String carNum) {
        PmsTemp temp = new PmsTemp();
        temp.setCarNum(carNum);
        temp.setCardId(getNum(0));
        temp.setTempId(getNum(1));
        temp.setEntryDate(new Date());
        temp.setEntryTime(new Date());
        return this.save(temp);
    }

    @Override
    public boolean outParking(String tempId) {

        settlement(tempId, Float.parseFloat("5.1"));

        PmsTemp temp = getTempById(tempId);
        temp.setOutTime(new Date());
        temp.setOutDate(new Date());

        UpdateWrapper<PmsTemp> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(PmsTemp::getTempId, tempId);

        return this.update(temp, updateWrapper);
    }


    @Override
    public PmsTemp getTempById(String tempId) {
        QueryWrapper<PmsTemp> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PmsTemp::getTempId, tempId);
        return baseMapper.selectOne(queryWrapper);
    }


    @Override
    public boolean settlement(String tempId, Float money) {
        PmsTemp temp = getTempById(tempId);
        temp.setOutTime(new Date());
        temp.setOutDate(new Date());
        Float res = getTempMoney(temp, money);
        if (res != null) {
            UpdateWrapper<PmsTemp> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .set(PmsTemp::getTempMoney, res)
                    .eq(PmsTemp::getTempId, tempId);
            this.update(updateWrapper);
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(String tempId) {
        UpdateWrapper<PmsTemp> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(PmsTemp::getTempId, tempId);

        return this.remove(updateWrapper);
    }

    /**
     * 计算停车费
     *
     * @param temp
     * @param money
     * @return
     */
    public Float getTempMoney(PmsTemp temp, Float money) {

        System.out.println(temp);
        long entry = temp.getEntryTime().getTime();
        long out = temp.getOutTime().getTime();

        long time = out - entry;
        long hour = (long) Math.ceil(time / (1000 * 60 * 60 * 1.0)); // 多少小时
        System.out.println(hour);
        return money * hour;


    }

    /**
     * 生成编号：生成规则:8位日期+6位以上自增id；
     * 0表示IC卡号
     * 1表示临时编号
     *
     * @return
     */
    public String getNum(int i) {
        // 编号
        StringBuilder sb = new StringBuilder();
        // 8位日期
        String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
        sb.append(yyyyMMdd);

        // 6位以上自增id
        // redis incr 原子性
        // 适合并发的自增方式：
        String key;
        if (i == 0) {
            key = REDIS_KEY_PREFIX_CARD_ID + yyyyMMdd;
        } else {
            key = REDIS_KEY_PREFIX_TEMP_ID + yyyyMMdd;

        }
        Long incr = redisService.incr(key, 1);
        // 拿到当前的6位以上自增 如果小于6位，自动补全0
        if (incr.toString().length() <= 6) {
            sb.append(String.format("%06d", redisService.incr(key, 1)));
        } else {
            // 如果是6位 不用补0
            sb.append(incr);
        }
        return sb.toString();
    }
}
